<template>
    <div class="app-container">
        <el-form label-width="auto">
            <div class="params head-form">
                <el-form-item label="支付状态" prop="receiptState">
                    <el-select v-model="params.receiptState" @change="init">
                        <el-option v-for="item, index in receiptState" :key="item" :value="index"
                            :label="item.name"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="支付日期" prop="date">
                    <el-date-picker v-model="params.date" type="daterange" start-placeholder="开始时间"
                        end-placeholder="结束时间" @change="init" value-format="YYYY-MM-DD hh:mm:ss" />
                </el-form-item>
                <el-form-item>
                    <el-input placeholder="请输入关键词" @blur="init" v-model="params.partnerName">
                        <template #prepend>
                            <el-select v-model="params.partnerType" placeholder="请选择" @change="init"
                                style="width: 115px">
                                <el-option v-for="item, index in type" :label="item" :value="Number(index)" />
                            </el-select>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-input placeholder="请输入关键词" @blur="init" v-model="params.slipCode">
                        <template #prepend>
                            <el-select v-model="params.slipType" placeholder="请选择" @change="init" style="width: 115px">
                                <el-option v-for="item, index in slipType" :label="item" :value="Number(index)" />
                            </el-select>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item label="已记账">
                    <el-select placeholder="请选择" @change="init" v-model="params.tallyStatus">
                        <el-option label="已记账" :value="1" />
                        <el-option label="未记账" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图片状态">
                    <el-select placeholder="请选择" @change="init" v-model="params.exceptionStatus">
                        <el-option label="正常" :value="0" />
                        <el-option label="异常" :value="1" />
                        <el-option label="已修复" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="付款账户">
                    <el-input placeholder="请输入" @blur="init" v-model="params.payAccount" />
                </el-form-item>
                <el-form-item label="支付金额">
                    <input-range v-model="params.amount" @change="init" />
                </el-form-item>
                <el-form-item>
                    <el-button :icon="RefreshRight" plain type="primary" @click="reset">重置</el-button>
                </el-form-item>
            </div>
        </el-form>
        <div class="total">
            <div>合计金额<span>（所有筛选记录）</span></div>
            <div>支付金额：<span>￥{{ totalMoney }}</span></div>
        </div>
        <div class="batch-btn">
            <el-button type="primary" @click="accounting(1)">批量记账</el-button>
            <el-button type="primary" @click="accounting(0)">批量取消记账</el-button>
            <el-button type="primary" @click="excel">导出</el-button>
        </div>
        <div class="table">
            <el-table :data="data" style="width: 100%" max-height="calc(100vh - 470px)"
                :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="40" />
                <el-table-column prop="recordCode" label="编号" width="160" />
                <el-table-column prop="slipType" label="业务单据类型" width="160">
                    <template #default="{ row }">
                        {{ slipType[row.slipType] }}
                    </template>
                </el-table-column>
                <el-table-column prop="slipType" label="合作方" width="200">
                    <template #default="{ row }">
                        {{ splicing([type[row.partnerType], row.partnerName], '：') }}
                    </template>
                </el-table-column>
                <el-table-column prop="slipCode" label="关联单据" min-width="200">
                    <template #default="{ row }">
                        <div class="link" @click="toPath({ slipCode: row.slipCode, type: row.slipType }, '关联单据')">
                            {{ row.slipCode }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="orderCode" label="关联业务单据" min-width="200">
                    <template #default="{ row }">
                        <div class="link" @click="toPath(row, '关联业务单据')">
                            {{ row.orderCode }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="receiptState" label="审批状态" width="120">
                    <template #default="scope">
                        <el-tag :type="receiptState[scope.row.receiptState].color">{{
                            receiptState[scope.row.receiptState].name }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="inMoney" label="支付金额" width="120">
                    <template #default="scope">
                        {{ (scope.row.type == 1 && scope.row.adjustType == 1) || (scope.row.type == 2 &&
                            scope.row.adjustType == 2) ?
                            '-' : '' }}￥{{ scope.row.inMoney }}
                    </template>
                </el-table-column>
                <el-table-column prop="platformName" label="支付平台" width="120"></el-table-column>
                <el-table-column prop="payName" label="支付方式" width="120" />
                <el-table-column prop="payAccount" label="付款账户" width="260">
                    <template #default="scope">
                        {{ scope.row.payAccount || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="receiptAccount" label="收款账户" width="260">
                    <template #default="scope">
                        {{ scope.row.receiptAccount || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="receiptDate" label="发生时间" width="180" />
                <el-table-column prop="recordType" label="流水类型" width="180">
                    <template #default="scope">
                        {{ recordType[scope.row.recordType]?.name }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="200">
                    <template #default="scope">
                        <el-button type="primary" link size="small" v-if="scope.row.processCode"
                            @click="openAudit(scope.row)">审批记录</el-button>
                        <el-button type="primary" link size="small" @click="openModal(scope.row)"
                            v-if="scope.row.adjust">纠错调整</el-button>
                        <el-button type="primary" link size="small" @click="openeditImg(scope.row)"
                            v-if="scope.row.exceptionStatus">修改图片</el-button>
                        <div v-if="(!scope.row.adjust) && (!scope.row.processCode) && (!scope.row.exceptionStatus)">--
                        </div>
                    </template>
                </el-table-column>
                <template #empty>
                    <el-empty />
                </template>
            </el-table>
        </div>
        <div class="pagination">
            <el-pagination v-model:current-page="query.current" v-model:page-size="query.size"
                :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                @size-change="init" @current-change="init" />
        </div>
        <el-dialog v-model="visible" width="500" center align-center :show-close="false" @close="resetEdit">
            <template #header>
                <custom-title title="纠错调整" />
            </template>
            <div class="code">支付流水编号：<span>{{ form.recordCode }}</span></div>
            <el-form :model="form" label-width="auto" ref="formRef" :rules="rules">
                <el-form-item label="本次调整类型" prop="adjustType">
                    <el-radio-group v-model="form.adjustType">
                        <el-radio label="红冲" :value="1" />
                        <el-radio label="蓝冲" :value="2" />
                    </el-radio-group>
                    <div class="tip">
                        注意：收款-红冲为负金额，付款-红冲为正金额
                    </div>
                </el-form-item>
                <el-form-item label="收款金额" prop="money">
                    <el-input placeholder="请输入" v-model="form.money" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input placeholder="请输入" type="textarea" v-model="form.remark" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="visible = false">取消</el-button>
                    <el-button type="primary" @click="comfirm">
                        提交审批
                    </el-button>
                </div>
            </template>
        </el-dialog>
        <EditImg v-model:show="visibleEditImg" v-if="visibleEditImg" v-model:imgs="editImgForm.fileVos"
            @comfirm="editImgComfirm" />
        <Audit v-model:show="visibleAudit" v-if="visibleAudit" :code="code" />
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { getList, edit, editReceiptImg, exportReceipt, batchRecord } from "@/apis/payments";
import { RefreshRight } from '@element-plus/icons-vue';
import { receiptState, recordType } from './config.js';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from "vue-router";
import { type } from "@/utils/config";
import { slipType, slipUrl } from "@/utils/config";
import { splicing } from "@/utils";
import Audit from "@/views/audit/index.vue";
import EditImg from "./components/EditImg.vue";
import exportExcel from "@/utils/exportExcel";

const route = useRoute();
const router = useRouter();
const visible = ref(false);
const visibleEditImg = ref(false)
const editImgForm = ref({
    recordId: '',
    fileVos: []
})
const checkedList = ref([]);
const tableRowClassName = ({ row }) => {
    if (row.recordType == 2 && row.adjustType == 1) {
        return recordType[2].class;
    } else {
        return recordType[1].class;
    }
}
const businessUrl = (type) => {
    let url = ''
    switch (type) {
        case 1:
            url = '/business/oder'
            break;
        case 2:
            url = '/business/procure/purchase-order'
            break;
        case 3:
            break;
        case 4:
            break;
        case 5:
            url = '/finance/reimbursed-manage'
            break;
        case 6:
        case 7:
            url = '/finance/loan-manage'
            break;
        case 8:
            break;
        case 9:
            break;
        default:
            break;
    }
    return url;
}
const toPath = (item, type) => {
    let path;
    switch (type) {
        case '关联单据':
            path = slipUrl(item.type);
            break;
        case '关联业务单据':
            if ((item.orderCode && item.orderCode.startsWith("HT")) && item.jumpUrl) {
                const originUrl = window.location.origin;
                window.open(originUrl + '/' + item.jumpUrl + item.orderCode, '_blank');
                return;
            }
            path = businessUrl(item.slipType);
            break;
        default:
            break;
    }
    let query;
    if (type == '关联业务单据' && [1, 2].includes(item.type)) {
        const { orderCode } = item;
        query = { code: orderCode }
    } else {
        query = item;
    }
    if (path) {
        const routeInfo = router.resolve({
            path,
            query
        });
        const url = routeInfo.href;
        window.open(url, '_blank')
    }
}

const form = ref({})
const query = ref({
    size: 10,
    current: 1
});
const visibleAudit = ref(false);
const formRef = ref(null)
const params = ref({
    receiptState: '2'
})
const data = ref([]);
const total = ref(0);
const totalMoney = ref(0);
const reset = () => {
    params.value = {};
    init()
}
/**
 * 重置表单
 */
const resetEdit = () => {
    form.value = {};
    formRef.value.resetFields();
}
/**
 * 转换参数
 */
const paramsConvert = () => {
    let payStartDate = params.value.date ? params.value.date[0] : undefined;
    let payEndDate = params.value.date ? params.value.date[1] : undefined;
    const minAmount = params.value.amount ? params.value.amount[0] : undefined;
    const maxAmount = params.value.amount ? params.value.amount[1] : undefined;
    const paramsData = {
        ...params.value,
        payStartDate,
        payEndDate,
        minAmount,
        maxAmount,
    }
    delete paramsData.amount;
    delete paramsData.date;
    return paramsData;
}
/**
 * 初始化
 */
const init = async () => {
    const res = await getList(query.value, paramsConvert());
    data.value = res.data.page.records;
    total.value = res.data.page.total;
    totalMoney.value = res.data.payMoney;
}
/**
 * 打开纠错弹窗
 */
const openModal = (item) => {
    form.value = { ...item };
    visible.value = true;
}
const rules = {
    adjustType: [{ required: true, message: '请选择调整类型', trigger: 'blur' }],
    money: [{ required: true, message: '请输入金额', trigger: 'blur' }, { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入正确的金额', trigger: 'blur' }],
    remark: [{ max: 100, message: '备注不能超过100个字符', trigger: 'blur' }]
}
/**
 * 纠错调整
 */
const comfirm = () => {
    formRef.value.validate(async (valid) => {
        if (!valid) return;
        const res = await edit(form.value);
        if (res.code == 200) {
            visible.value = false;
            ElMessage.success('操作成功');
            init();
        }
    })
}
const code = ref('')
/**
 * 打开审批弹窗
 */
const openAudit = (item) => {
    visibleAudit.value = true;
    code.value = item.processCode
}
const openeditImg = (item) => {
    visibleEditImg.value = true;
    editImgForm.value.recordId = item.recordId;
    if (item.payPicUrls) {
        editImgForm.value.fileVos = item.payPicUrls?.split(',').map((v, i) => ({
            fileUrl: v,
            fileId: item.payPicIds?.split(',')[i],
            fileName: v.split('/').pop()
        }));
    } else {
        editImgForm.value.fileVos = [];
    }

}
/**
 * 确定修改图片
 */
const editImgComfirm = async () => {
    const res = await editReceiptImg(editImgForm.value);
    if (res.code == 200) {
        ElMessage.success('操作成功');
        visibleEditImg.value = false;
        init();
    }
}
/**
 * 导出流水
 */
const excel = async () => {
    const res = await exportReceipt(paramsConvert());
    exportExcel(res, '收支流水')
}
const handleSelectionChange = (newSelection) => {
    checkedList.value = newSelection.map(v => v.recordId);
}
/**
 * 改变记账状态
 */
const accounting = async (tallyStatus) => {
    if (!checkedList.value.length) return ElMessage.error('请选择要操作的数据');
    const res = await batchRecord({ tallyStatus, recordIds: checkedList.value });
    if (res.code == 200) {
        ElMessage.success('操作成功')
        init()
    };
}
onMounted(() => {
    params.value.slipCode = route.query.slipCode;
    params.value.slipType = route.query.slipType ? Number(route.query.slipType) : null;
    init()
})
</script>

<style lang="scss" scoped>
.params {
    display: grid;
    grid-template-columns: repeat(4, 2fr);
    column-gap: 20px;

    .el-button--primary {
        background: #007DFF;
        border-radius: 0;
        border: none;
    }

    .is-plain {
        border: 1px solid #007DFF;
        background: none;

        &:hover {
            background: none;
            color: #007DFF;
        }
    }

    ::v-deep(.el-checkbox__label) {
        color: unset;
    }

    ::v-deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
        background: $topic;
        border: 1px solid $topic;
    }

    ::v-deep(.el-date-editor.el-input__wrapper) {
        width: unset;
    }
}

.batch-btn {
    margin-bottom: 10px;
}

.total {
    height: 50px;
    background: #F6F8FA;
    color: #3D3D3D;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10px;
    margin-bottom: 20px;

    span {
        color: rgb(134, 144, 156);
    }
}

.table {
    border: $border;

    ::v-deep(.el-table tr) {
        height: 46px;

        .is-link {
            color: $topic;
        }

        td,
        th {
            border-bottom: $border !important;
        }

        .cell {
            display: flex;
            justify-content: center;
        }
    }

    ::v-deep(.el-table thead tr) {
        background: #F2F6FC;

        >th {
            background: transparent;
            text-align: center;
        }

        .el-table-fixed-column--right {
            background: #F2F6FC;
        }

    }

    ::v-deep(.el-table tbody tr) {
        .el-table-fixed-column--right {
            background: white;
        }
    }

    ::v-deep(.blue) {
        background: #BFDEFF !important;
    }

    ::v-deep(.red) {
        background: rgba(255, 0, 0, 0.23);
    }

    ::v-deep(.el-table__inner-wrapper) {
        &::before {
            display: none;
        }
    }

    ::v-deep(.hover-row) {
        >td.el-table__cell {
            background-color: unset !important;
        }

        >td.el-table-fixed-column--right {
            background: white !important;
        }
    }

    ::v-deep(.el-table tbody tr:last-child) {
        td {
            border-bottom: none !important;
        }

    }

    ::v-deep(.el-table__inner-wrapper) {
        &::before {
            display: none;
        }
    }

    .link {
        color: $topic;
        cursor: pointer;
        text-decoration: underline;
    }
}

.dialog-footer {
    .el-button--primary {
        background: #007DFF;
        border-radius: 0;
        border: none;
    }

    .el-button {
        border-radius: 0;
    }
}

.code {
    color: black;
    font-size: 16px;
    margin-bottom: 10px;
}

.params-btn {
    flex: 1;
    display: flex;
    justify-content: end;
}
</style>